import { PlusOutlined } from '@ant-design/icons';
import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';

import { createDevice } from '@/services/api/device';
import { getDeviceTypeList } from '@/services/api/deviceType';
import { Button, message } from 'antd';
import React from 'react';
type CreateFormProps = {
  onCancel?: () => void;
  onSubmit: (values: API.CreateDeviceParams) => void;
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const { onSubmit } = props;
  const onOpenChange = () => {};

  return (
    <ModalForm<API.CreateDeviceParams>
      title="添加设备"
      modalProps={{
        // 关闭弹框是否销毁 (相当于直接进行了表单重置)
        destroyOnClose: true,
      }}
      trigger={
        <Button type="primary">
          <PlusOutlined />
          新建
        </Button>
      }
      onOpenChange={() => onOpenChange()}
      onFinish={async (values) => {
        console.log(values);
        await createDevice({
          deviceAccounts: [],
          metadata: {},
          ...values,
        });
        onSubmit(values);
        message.success('提交成功');
        // 返回true 则关闭
        return true;
      }}
      initialValues={{}}
    >
      <ProFormText
        label="Token"
        name="token"
        rules={[
          {
            required: true,
            message: '请输入Token',
          },
        ]}
        placeholder="请输入Token"
      />

      <ProFormText
        label="名称"
        name="name"
        rules={[
          {
            required: true,
            message: '请输入名称',
          },
        ]}
        placeholder="请输入名称"
      />
      <ProFormSelect
        name="deviceTypeToken"
        label="设备类型"
        request={async () => {
          const msg = await getDeviceTypeList();
          const results = msg?.results;
          return results.map((item) => {
            return {
              label: item.name,
              value: item.token,
            };
          });
        }}
        placeholder="请选择"
        rules={[{ required: true, message: '请选择' }]}
      />
      <ProFormTextArea label="备注" name="comments" placeholder="请输入备注" />
    </ModalForm>
  );
};

export default CreateForm;
